var $issueInvoiceList=$("#issueInvoiceTab")
var companyIdHeader='',rowsList=''
$(function () {
    ApplyOrderFun() // 查看发票申请详情
    // issueInvoiceFun()
     // table


})

function ApplyOrderFun() {
    // 查看发票申请详情
//    /orderInvoice/selectApplyOrderInvoiceInfo
    let dataJson={
        chsCustomerOrderInvoiceId:$("#chsCustomerOrderInvoiceId").val()
    }
    $.ajax({

        url: '/orderInvoice/selectApplyOrderInvoiceInfo',
        type: 'POST',
        dataType: "json",
        data: {
            chsCustomerOrderInvoiceId:$("#chsCustomerOrderInvoiceId").val()
        },
        success:function (data,status) {
            if(data.code=='000000'){
                $("#createPeopleName").html(data.data.createPeopleName || '暂无')
                $("#createTm").html(data.data.createTm || '暂无')
                $("#companyName").html(data.data.companyName || '暂无')
                switch(data.data.invoiceType){
                    case 1:
                        $("#invoiceType").html('纸质发票');
                        break;
                    case 2:
                        $("#invoiceType").html('电子发票');
                        break;
                    case 3:
                        $("#invoiceType").html('纸质专票');
                        break;
                    default:
                        $("#invoiceType").html('暂无');
                }
                // $("#invoiceType").html(data.data.invoiceType || '暂无')
                $("#invoiceCompanyName").html(data.data.invoiceCompanyName || '暂无')
                $("#invoiceTitle").html(data.data.invoiceTitle || '暂无')
                $("#taxNumber").html(data.data.taxNumber || '暂无')
                $("#address").html(data.data.address || '暂无')
                $("#phone").html(data.data.phone || '暂无')
                $("#bankAddress").html(data.data.bankAddress || '暂无')
                $("#bankAccount").html(data.data.bankAccount || '暂无')
                $("#invoiceMoney").html(data.data.invoiceMoney || '暂无')
                $("#sendEmail").html(data.data.sendEmail || '暂无')
                $("#payee").html(data.data.payee || '暂无')
                $("#reviewer").html(data.data.reviewer || '暂无')
                $("#makePerson").html(data.data.makePerson || '暂无')
                $("#remark").html(data.data.remark || '暂无')
                companyIdHeader=data.data.companyId
                issueInvoiceFun()
                $("#companyId").val(data.data.companyId)

            }else{
                $.alert(data.message);
            }
        },
        error: (function (res) {
            $.alert("保存失败");
        })
    })
}

var productFormat = {
    typeFun: function (value, row, index, field){
        let val_set=row.type || ''
        value == null ? val_set = '' : val_set = value;
        let inputHtml = '<input type="text" value="'+val_set+'" placeholder="请输入" class="form-control" >';
        row.type = val_set || $(inputHtml).val();
        return inputHtml;
    },
    //单位
    unitFun: function (value, row, index, field){
        let val_set=row.unit || ''
        value == null ? val_set = '' : val_set = value;
        let inputHtml = '<input type="text" value="'+val_set+'" placeholder="请输入" class="form-control" >';
        row.unit = val_set || $(inputHtml).val();
        return inputHtml;
    },
    //单价
    unitPriceFun: function (value, row, index, field){
        let val_set=row.unitPrice || ''
        value == null ? val_set = '' : val_set = value;
        let inputHtml = '<input type="text" value="'+val_set+'" placeholder="请输入" class="form-control" >';
        row.unitPrice = val_set || $(inputHtml).val();
        return inputHtml;
    },
    //quantity 数量
    quantityFun: function (value, row, index, field){
        let val_set=row.quantity || ''
        value == null ? val_set = '' : val_set = value;
        let inputHtml = '<input type="text" value="'+val_set+'" placeholder="请输入" class="form-control" >';
        row.quantity = val_set || $(inputHtml).val();
        return inputHtml;
    },
    // 金额 invoiceMoney
    invoiceMoneyFun: function (value, row, index, field){
        let val_set=row.invoiceMoney || ''
        //
        value == null ? val_set = '' : val_set = value;

        let inputHtml = '<input type="text" value="'+val_set+'" placeholder="请输入" class="form-control" onkeyup="value=value.replace(/^\\D*(\\d*(?:\\.\\d{0,2})?).*$/g, \'$1\')">';
        row.invoiceMoney = val_set || $(inputHtml).val();
        return inputHtml;
    },
    //税率 taxRate
    taxRateFun: function (value, row, index, field){
        let val_set=row.taxRate || ''
        value == null ? val_set = '' : val_set = value;
        let inputHtml = '<input type="text" value="'+val_set+'" placeholder="请输入" class="form-control" >';
        row.taxRate = val_set || $(inputHtml).val();
        return inputHtml;
    },
    //税额
    taxMoneyFun: function (value, row, index, field){
        let val_set=row.taxMoney || ''
        value == null ? val_set = '' : val_set = value;

        let inputHtml = '<input type="text" value="'+val_set+'" placeholder="请输入" class="form-control" >';
        row.taxMoney = val_set || $(inputHtml).val();
        return inputHtml;
    },


}

var htmlFormat={
    typeEvent:{
        'change input': function (e, value, row, index) {



            productFormat.typeFun($(e.target).val(), row);
        },
        'click input': function (e, value, row, index) {

            e.stopPropagation( )
        }
    },
    unitEvent:{
        'change input': function (e, value, row, index) {



            productFormat.unitFun($(e.target).val(), row);
        },
        'click input': function (e, value, row, index) {

            e.stopPropagation( )
        }
    },
    unitPriceEvent:{
        'change input': function (e, value, row, index) {



            productFormat.unitPriceFun($(e.target).val(), row);
        },
        'click input': function (e, value, row, index) {

            e.stopPropagation( )
        }
    },
    quantityEvent:{
        'change input': function (e, value, row, index) {



            productFormat.quantityFun($(e.target).val(), row);
        },
        'click input': function (e, value, row, index) {

            e.stopPropagation( )
        }
    },
    invoiceMoneyEvent:{
        'change input': function (e, value, row, index) {



            productFormat.invoiceMoneyFun($(e.target).val(), row);
            // $('#issueInvoiceTab').bootstrapTable('updateRow', {
            //     index,
            //     replace: true,
            //     row
            // });

            // e.stopPropagation();
        },
        'click input': function (e, value, row, index) {

            e.stopPropagation( )
        }
    },
    taxRateEvent:{
        'change input': function (e, value, row, index) {



            productFormat.taxRateFun($(e.target).val(), row);
        },
        'click input': function (e, value, row, index) {

            e.stopPropagation( )
        }
    },
    taxMoneyEvent:{
        'change input': function (e, value, row, index) {



            productFormat.taxMoneyFun($(e.target).val(), row);
        },
        'click input': function (e, value, row, index) {

            e.stopPropagation( )
        }
    }
}

$('table').on('load-success.bs.table', function (e,data) {
    $(e.target).find('label.lyear-checkbox').on('click', function (e) {

        setTimeout(function () {
            rowsList=$issueInvoiceList.bootstrapTable('getSelections')
            $("#issueInvoiceTab tbody  td input[type=text]").attr("disabled", false)
            $("#issueInvoiceTab tbody .selected td input[type=text]").attr("disabled", true)
            for (let i = 0, len = rowsList.length; i < len; i++) {
                if (rowsList[i].invoiceMoney == '' || rowsList[i].invoiceMoney==null) {
                    $.alert('金额不能为空！')
                    return false;
                }
                if (rowsList[i].invoiceMoney ==0 ) {
                    $.alert('金额不能为零！')
                    return false;
                }
                if (rowsList[i].taxRate == '' || rowsList[i].taxRate==null) {
                    $.alert('税率不能为空！')
                    return false;
                }
            }
        },500)
        e.stopPropagation();
    })

})

$issueInvoiceList.on('click',function () {

    $("#issueInvoiceTab tbody  td input[type=text]").attr("disabled", false)
    $("#issueInvoiceTab tbody .selected td input[type=text]").attr("disabled", true)

    rowsList=$issueInvoiceList.bootstrapTable('getSelections')





    for (let i = 0, len = rowsList.length; i < len; i++) {
        if (rowsList[i].invoiceMoney == '' || rowsList[i].invoiceMoney==null) {
            $.alert('金额不能为空！')
            return false;
        }
        if (rowsList[i].invoiceMoney ==0 ) {
            $.alert('金额不能为零！')
            return false;
        }
        if (rowsList[i].taxRate == '' || rowsList[i].taxRate==null) {
            $.alert('税率不能为空！')
            return false;
        }
    }

})



function submitTable() {
    rowsList=$issueInvoiceList.bootstrapTable('getSelections');
    if(rowsList.length<0){
        $.alert('请先选中！')
    }else{
        for (let i = 0, len = rowsList.length; i < len; i++) {
            if (rowsList[i].invoiceMoney == '' || rowsList[i].invoiceMoney==null) {
                $.alert('金额不能为空！')
                return false;
            }
            if (rowsList[i].invoiceMoney ==0 ) {
                $.alert('金额不能为零！')
                return false;
            }
            if (rowsList[i].taxRate == '' || rowsList[i].taxRate==null) {
                $.alert('税率不能为空！')
                return false;
            }
            rowsList[i]['chsCustomerOrderInvoiceId']=$("#chsCustomerOrderInvoiceId").val()
        }
        console.log(rowsList,'rowsList')
        $.ajax({
            url: '/orderInvoice/addOrderInvoiceLog',
            type: 'POST',
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(rowsList),
            success:function (result) {
                console.log(result)
                if(result.code=='000000'){
                    $.alert({
                        title: '提示',
                        content: '操作成功！',
                        buttons: {
                            confirm: {
                                text: '确认',
                                btnClass: 'btn-primary',
                                action: function () {
                                    parent.$(parent.document).data('multitabs').create({
                                        iframe: true,
                                        title: '开票记录',
                                        url: "/front/finance/invoiceForm"
                                    },true);

                                    // var $thisTabs = parent.$('.mt-nav-bar .nav-tabs').find('li.active');
                                    // var navTab = parent.$multitabs._getNavTab($thisTabs);
                                    // //关闭当前页签
                                    // closeTab(navTab);
                                    // //打开首页
                                    // openTab("开票记录","/front/finance/invoiceForm");
                                    // delStorageAndRemove(navTab);
                                }
                            }
                        }
                    });

                }else{
                    $.alert(result.message)
                }
            },
            error:function (err) {
                $.alert(err.message)
            }
        })
    }
}

function issueInvoiceFun() {
    $issueInvoiceList.bootstrapTable('destroy');
    $issueInvoiceList.bootstrapTable({
        classes: 'table table-hover table-bordered table-striped',
        url: '/companyProject/selectCompanyProjectListT',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,                      // 是否显示行间隔色
        sortable: true,                     // 是否启用排序
        sortOrder: "desc",                  // 排序方式
        sortName: 'createTm',               // 排序字段
        cache: false,                       // 是否使用缓存
        showColumns: false,                 // 显示隐藏列
        showRefresh: false,                 // 显示刷新按钮
        showToggle: false,                  // 切换显示样式
        showFooter: false,                  // 显示Table脚部
        pagination: true,                   // 是否显示分页


        showPaginationSwitch: false,        // 是否显示分页按钮
        clickToSelect: true,                // 是否启用点击选中行
        maintainSelected: true,             // 分页是否保留选中
        singleSelect: false,
        minimumCountColumns: 2,             // 最少要显示的列数
        undefinedText: '-',                  // cell没有值时显示
        sidePagination: "server",           // 分页方式：client客户端分页，server服务端分页
        // serverSort: true,
        uniqueId: 'customerProductId',
        idField: 'customerProductId',
        pageSize: 5,                        // 每页的记录行数
        pageNumber: 1,                      // 初始化加载第1页，默认第1页
        pageList: "[5, 10, 15, 20]",        // 可供选择的每页的行数

        queryParams: function (params) {
            params.pageSize = params.limit;
            params.pageIndex = (params.offset / params.limit) + 1;
            params.companyId = companyIdHeader;
            return params;
        },//查询参数





        columns: [

            {title: '主键', field: 'customerProductId', visible: false},
            {checkbox: true, visible: true},
            {title: '项目名称', field: 'projectName', align: 'left', valign: 'middle'},
            {title: '规格型号', field: 'type', align: 'left', valign: 'middle', events: htmlFormat.typeEvent,formatter: productFormat.typeFun},
            {title: '单位', field: 'unit', align: 'left', valign: 'middle', events: htmlFormat.unitEvent,formatter: productFormat.unitFun},
            {title: '单价', field: 'unitPrice', align: 'left', valign: 'middle', events: htmlFormat.unitPriceEvent,formatter: productFormat.unitPriceFun},
            {title: '数量', field: 'quantity', align: 'left', valign: 'middle', events: htmlFormat.quantityEvent,formatter: productFormat.quantityFun},
            {title: '金额', field: 'invoiceMoney', align: 'left', valign: 'middle', width: '160', events: htmlFormat.invoiceMoneyEvent, formatter: productFormat.invoiceMoneyFun},
            {title: '税率', field: 'taxRate', align: 'left', valign: 'middle', width: '160', events: htmlFormat.taxRateEvent, formatter: productFormat.taxRateFun},

            {title: '税额', field: 'taxMoney', valign: 'middle', events: htmlFormat.taxMoneyEvent, formatter: productFormat.taxMoneyFun},
        ],
        responseHandler: function (result) {
            if(result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };



            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {

        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                // alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}
function OrderDetail() {
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: '订单详情',
        url: "/front/finance/orderInfoByNumber?productOrderNumber="+$(".order-name").text()
    },true);
}
function resetTable() {
    $("#issueInvoiceTab input").val('')
}


